﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region Using
using System;
using System.Collections.Generic;
using System.ServiceModel.DomainServices.Server;
using System.Web;
using NetBay.Core.BusinessEntities;
using NetBay.Core.Log;
using Rio.Framework.RioManager;
using Rio.Doc.Business.Repository;
#endregion

namespace Rio.Applications.Web.Services
{
    /// <summary>
    /// Class to handle Business entities in a RIA services
    /// </summary>
    public partial class BusinessEntitiesDomainService : DomainService
    {
        /// <summary>
        /// Disconnect the user from session
        /// </summary>
        [Invoke]
        public void Disconnect()
        {
            try
            {
                // Get the Current user
                User l_oUser = GetUser();

                // Add a historic of user action
                AddActionHistoric((int)Constant.UserActions.DECONNEXION, 0, 0, null, null);

                // Remove the rioscan file for this user
                RemoveRioscanFileUser(l_oUser.RefreshScanGuid, AppDomain.CurrentDomain.BaseDirectory + @"\Rioscan");

                // Remove the user from Session
                HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()] = null;
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(" EXCEPTION -> " + Environment.NewLine + ex);
            }
        }

        /// <summary>
        /// Get the user in session 
        /// </summary>
        /// <returns>the User</returns>
        [Query]
        public IEnumerable<User> GetCurentUser()
        {
            List<User> l_oUsers = new List<User>();

            try
            {
                // Get the Current user
                User l_oUser = GetUser();

                l_oUsers.Add(l_oUser);
            }
            catch (Exception ex)
            {
                User l_oUser = new User("()", ex);
                //NetBay.Core.Log.LogManager.Instance().LogError(l_oUser.FullErrorMessage);
                l_oUsers.Add(l_oUser);

                //NetBay.Core.Log.LogManager.Instance().LogError(" EXCEPTION -> " + Environment.NewLine + ex);
            }

            return l_oUsers;
        }

        /// <summary>
        /// Retreive if the user in session 
        /// </summary>
        /// <returns>true (in session) otherwise false</returns>
        [Invoke]
        public bool IsUserLogged()
        {
            bool l_bRet = false;

            try
            {
                l_bRet = HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()] != null;
            }
            catch (Exception ex)
            {
                l_bRet = false;
                NetBay.Core.Log.LogManager.Instance().LogError(ex.ToString());
            }
            return l_bRet;
        }

        /// <summary>
        /// Gets all users.
        /// </summary>
        /// <returns></returns>
        [Query]
        public IEnumerable<User> GetAllUsers()
        {
            List<User> l_lstUser = new List<User>();

            try
            {
                l_lstUser = UserRepository.FindAllUser();
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(GetType().FullName + ") exception : " + ex.Message);
            }
            return l_lstUser;
        }

        /// <summary>
        /// Gets the users by folder type id.
        /// </summary>
        /// <param name="folderTypeId">The folder type id.</param>
        /// <returns></returns>
        [Query]
        public IEnumerable<User> GetUsersByFolderTypeId(long folderTypeId)
        {
            List<User> l_lstUser = new List<User>();

            try
            {
                l_lstUser = Rio.Doc.Business.Repository.UserRepository.GetUsersByFolderTypeId(folderTypeId);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(GetType().FullName + ") exception : " + ex.Message);
            }
            return l_lstUser;
        }


        /// <summary>
        /// Gets the users by folder id.
        /// </summary>
        /// <param name="folderId">The folder id.</param>
        /// <returns></returns>
        [Query]
        public IEnumerable<User> GetUsersByFolderId(string folderId)
        {
            List<User> l_lstUser = new List<User>();

            try
            {
                l_lstUser = Rio.Doc.Business.Repository.UserRepository.GetUsersByFolderId(folderId);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(GetType().FullName + ") exception : " + ex.Message);
            }
            return l_lstUser;
        }

        /// <summary>
        /// Adds the authorisations doc.
        /// </summary>
        /// <param name="folderId">The P_S folder id.</param>
        /// <param name="userIdList">The P_L user id list.</param>
        /// <param name="P_lFolderId">The P_L folder id.</param>
        /// <param name="P_lFolderTypeId">The P_L folder type id.</param>
        [Invoke(HasSideEffects = true)]
        public void AddAuthorisationsDoc(string folderId, List<long> userIdList, long P_lFolderId, long P_lFolderTypeId)
        {
            try
            {
                AddActionHistoric((int)Constant.UserActions.MODIFICATION_AUTORISATIONS, P_lFolderTypeId, P_lFolderId, null, "");
                foreach (long L_lUserId in userIdList)
                {
                    Rio.Doc.Business.Repository.UserRepository.AddAuthorisationsDoc(folderId, L_lUserId);
                }
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(ex.ToString());
            }
        }

        /// <summary>
        /// Deletes the authorisations doc.
        /// </summary>
        /// <param name="P_sFolderId">The P_S folder id.</param>
        /// <param name="P_lUserIdList">The P_L user id list.</param>
        /// <param name="P_lFolderId">The P_L folder id.</param>
        /// <param name="P_lFolderTypeId">The P_L folder type id.</param>
        [Invoke(HasSideEffects = true)]
        public void DeleteAuthorisationsDoc(string P_sFolderId, List<long> P_lUserIdList, long P_lFolderId, long P_lFolderTypeId)
        {
            try
            {
                AddActionHistoric((int)Constant.UserActions.MODIFICATION_AUTORISATIONS, P_lFolderTypeId, P_lFolderId, null, "");
                foreach (long L_lUserId in P_lUserIdList)
                {
                    Rio.Doc.Business.Repository.UserRepository.DeleteAuthorisationsDoc(P_sFolderId, L_lUserId);
                }
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(ex.ToString());
            }
        }

        /// <summary>
        /// Add a user's action
        /// </summary>
        /// <param name="p_iUserActions">the user's action</param>
        /// <param name="p_lFolderTypeId">the folder type identifier</param>
        /// <param name="p_lFolderId">the flder Identifier</param>
        /// <param name="p_sDocumentId">the document Identifier</param>
        /// <param name="p_sFileName">The original filename</param>
        /// <returns>
        /// The identifier of the message flow
        /// </returns>
        /// <remarks>
        /// User do not know if this operation fails or not (explicit request)
        /// </remarks>
        [Query(HasSideEffects = true)]
        public IEnumerable<ReturnObject> AddActionHistoric(int p_iUserActions, long p_lFolderTypeId, long p_lFolderId, string p_sDocumentId, string p_sFileName)
        {
            List<ReturnObject> l_oRet = new List<ReturnObject>();

            Constant.UserActions l_iUserAction = Constant.UserActions.None;
            try
            {
                l_iUserAction = (Constant.UserActions)Enum.Parse(typeof(Constant.UserActions), p_iUserActions.ToString());

                UserRepository.AddUserAction(GetUser().UserId, l_iUserAction.szGetDescription(), p_lFolderTypeId, p_lFolderId, p_sDocumentId, p_sFileName, null, null, 0,  false);
                l_oRet.Add(new ReturnObject());
            }
            catch (Exception ex)
            {
                ReturnObject l_oReturnObject = new ReturnObject("(p_sAction<" + l_iUserAction.szGetDescription() + "> p_lFolderTypeId<" + p_lFolderTypeId + "> p_lFolderId<" + p_lFolderId + "> p_sDocumentId<" + p_sDocumentId + "> p_sFileName<" + p_sFileName + ">)...", ex);
                NetBay.Core.Log.LogManager.Instance().LogError(l_oReturnObject.FullErrorMessage);
                l_oRet.Add(l_oReturnObject);
            }

            return l_oRet;
        }

        /// <summary>
        /// Updates the user password.
        /// </summary>
        /// <param name="p_lUserId">The P_L user id.</param>
        /// <param name="p_sOldPassword">The P_S old password.</param>
        /// <param name="p_sNewPassword">The P_S new password.</param>
        /// <returns></returns>
        [Invoke]
        public ReturnBoolean UpdateUserPassword(long p_lUserId, string p_sOldPassword, string p_sNewPassword)
        {
            ReturnBoolean returnSuccess = new ReturnBoolean(false);

            try
            {
                NetBay.Core.Log.LogManager.Instance().LogDebug("(p_lUserId<" + p_lUserId.ToString() + "> p_sOldPassword<" + p_sOldPassword + "> p_sNewPassword<" + p_sNewPassword + ">)...");

                returnSuccess.Value = UserRepository.UpdateUserPassword(p_lUserId, p_sOldPassword, p_sNewPassword);
            }
            catch (Exception e)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in UpdateUserPassword : " + e.Message);

                returnSuccess.Value = false;
                returnSuccess.ErrorMessage = e.Message;
            }

            return returnSuccess;
        }

    }
}
